package com.landmark;

import java.awt.EventQueue;
import java.io.FileWriter;
import java.net.SocketTimeoutException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class RedKapCat extends SwingWorker<Boolean, Boolean> {

    FileWriter fw = null;
    FileWriter errorFile = null;
    int pageNo;
    StringBuffer sb = new StringBuffer();
    Hashtable<String, String> htModelLinks = new Hashtable<String, String>();
    Vector<String> vecMenuLinks = new Vector<String>();
    String status = "";
    JTextArea txtArea;
    UMProgressBar pBar = null;
    int lineCount = 0;


    @Override
    protected Boolean doInBackground() throws Exception {
        start();
        return true;
    }

    @Override
    protected void done() {
        Util.taskCompleteMsg(status);
    }

    public void start() {
        try {
            String dirName = "./outputs";
            String imagesPath = "./outputs/RedkapImages";
            String barcoSwatchesPath = "./outputs/RedkapSwatches";

            Util.createDirectory(dirName);
            Util.createDirectory(imagesPath);
            Util.createDirectory(barcoSwatchesPath);

            txtArea = Util.createOutputFile("RedKap");
            HelperBean helperBean = Util.getHelperBean();

            fw = new FileWriter(helperBean.getOutputFile());
            errorFile = new FileWriter(helperBean.getErrorFile());
            processLeftNavMenu();
            // Here we get all the search pages from page 0 to 9 which we know by seeing the site
            Enumeration<String> enume = vecMenuLinks.elements();
            while( enume.hasMoreElements()) {
                if (Util.getHelperBean().isTerminateCurrentProcess()) {
                    break;
                }
                String str = enume.nextElement();
                txtArea.setText(str);
                txtArea.paintImmediately(txtArea.getVisibleRect());
                processCategoryPage(str);                
            }
            

            txtArea.append("\nFiles are located at : \n" + helperBean.getOutputFile().getAbsolutePath() + "\n" + helperBean.getErrorFile().getAbsolutePath() + "\n");
            txtArea.append("Total products : " + htModelLinks.size() + "\n");
            txtArea.paintImmediately(txtArea.getVisibleRect());
            Util.getHelperBean().setLineCount(htModelLinks.size());

            iterateCollection(htModelLinks);

            if (fw != null) {
                fw.close();
            }

        } catch (Exception e) {
            status = e.toString();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (Exception e1) {
                // TODO: handle exception
            }
        }
        if( status.trim().equals(""))
            status = "Done processing.";
        if (Util.getHelperBean().isTerminateCurrentProcess()) {
            status = "Process Terminated";
        }
        txtArea.append("\n" + status);
    }

    /**
     *
     * @param htLinks
     */
    private void iterateCollection(Hashtable<String, String> htLinks) {
        try {
            lineCount = 0;
            pBar = new UMProgressBar();
            Enumeration<String> keys = htLinks.keys();
            fw.write("Product_Name, Description, Product_Image_URL\n");
            while (keys.hasMoreElements()) {
                if (Util.getHelperBean().isTerminateCurrentProcess()) {
                    break;
                }
                String key = (String) keys.nextElement();
                txtArea.append("Processing page: " + key + "\n");
                txtArea.paintImmediately(txtArea.getVisibleRect());
                sb = new StringBuffer();
                Util.getHelperBean().setCurrentCount(lineCount++);

                processModels(htLinks.get(key).toString());
                fw.write(sb.toString().replaceAll("\n", "").replace("   ", "").replaceAll("<#NEWLINE#>", "\n"));
                fw.flush();
                if( Util.getHelperBean().getLineCount() == lineCount ) {
                    Util.getHelperBean().setProcessingDone(true);
                    pBar.close();
                }
                EventQueue.invokeLater(pBar);
            }
        } catch (Exception e) {
        }
    }

    /**
     *
     * @param aUrl
     */
    private void processModels(String aUrl) {
        try {
            Parser parser = Util.getParserFromUrl(aUrl, null);

            NodeList nl = parser.parse(null);
            String prdtNameLs = Util.getHelperBean().getInputHTML().select(".current").text();

            String prdtDescLs = Util.getHelperBean().getInputHTML().select(".productRomanceText").text();
            prdtDescLs += Util.getHelperBean().getInputHTML().select(".productFeatures").text();
            Elements prdtImages = Util.getHelperBean().getInputHTML().select(".productImageContainer").select("img[src$=.jpg]");
            Elements prdtSwatches = Util.getHelperBean().getInputHTML().select(".productSwatches").select("li");
//            System.out.println(prdtSwatches);
            // gets all the main images
            sb.append(prdtNameLs.replaceAll(",", "&#44;"));
            sb.append(",");
            sb.append(prdtDescLs.replaceAll(",","&#44;"));
            sb.append(",");
            for (Element ele : prdtImages) {
                sb.append(ele.absUrl("src"));
                Util.saveImage(ele.absUrl("src"), "./outputs/RedkapImages", null);
            }
            sb.append("<#NEWLINE#>");
            // gets all the swatches
            for (Element ele : prdtSwatches) {                
                String imageUrl = ele.attr("style").substring(ele.attr("style").indexOf("'")+1,ele.attr("style").lastIndexOf("'"));
                Util.saveImage(imageUrl, "./outputs/RedkapSwatches", null);
            }
        } catch (SocketTimeoutException e) {
            try {
                processModels(aUrl);
            } catch (Exception e1) {
            }
        } catch (Exception e2) {
            try {
                errorFile.write(aUrl + " \n" + e2.getMessage() + " \n");
                errorFile.flush();
            } catch (Exception e1) {
            }
        }
    }

//    /**
//     *
//     * @param aNodeList
//     */
//    private void iterateTag(Node aNodeList) {
//        //try{
//        //sb = new StringBuffer();
//        if (aNodeList instanceof TextNode) {
//            // downcast to TextNode
//            TextNode text = (TextNode) aNodeList;
//            // do whatever processing you want with the text
//            //System.out.println (text.getText ());
//            sb.append(text.getText());
//
//        } else if (aNodeList instanceof TagNode) {
//
//            // downcast to TagNode
//            TagNode tag = (TagNode) aNodeList;
//
//            // process recursively (nodes within nodes) via getChildren()				
//            NodeList nl = tag.getChildren();
//            if (null != nl) {
//                try {
//                    for (NodeIterator i = nl.elements(); i.hasMoreNodes();) {
//                        iterateTag(i.nextNode());
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }

    private void processCategoryPage(String aUrl) {
        try {
            System.out.println(aUrl.substring(aUrl.indexOf("//")+2));
            Document doc = Jsoup.connect(aUrl).timeout(100*1000).get();
            Elements elements = doc.select("div.productDisplay").select("a[href]");
            System.out.println(elements.size());
            for (Element element : elements) {
                String absoluteUrl = element.attr("abs:href");
                htModelLinks.put(absoluteUrl, absoluteUrl);
            }
        } catch (SocketTimeoutException e) {
            try {
                processCategoryPage(aUrl);
            } catch (Exception e1) {
            }
        } catch (Exception e2) {
            try {
                errorFile.write(aUrl + " \n" + e2.getMessage() + " \n");
                errorFile.flush();
            } catch (Exception e1) {
            }
        }
    }

    private void processLeftNavMenu() {
        try {
        Parser parser = Util.getParserFromUrl("http://www.redkap.com/view/men%27s-wrangler-denim-shirt/438864", null);
        
        Document doc = Util.getHelperBean().getInputHTML();
        Elements elements = doc.select("div.catNav").select("a[href]");
            System.out.println(elements.size());
            for (Element element : elements) {
                
                String absoluteUrl = element.attr("abs:href");
                System.out.println(absoluteUrl);
                vecMenuLinks.add(absoluteUrl);
            }
        } catch (SocketTimeoutException e) {
            processLeftNavMenu();
        }    catch( Exception e1 ) {
            try {
                errorFile.write(" \n" + e1.getMessage() + " \n");
                errorFile.flush();
            } catch (Exception e2) {
            }
        }
                
    }
}
